﻿using QuanLyNganHangDe.DAL.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QuanLyNganHangDe.GUI.TacNghiep
{
    using BLL;

    public partial class FormQuanLyDeThi_Export : Form
    {
        private MySortableBindingList<DeInRa> _lstDeThi;
        private DotThi _dotThi;
        private HocKy _hocKy;
        private NamHoc _namHoc;
        private DAL.Models.QLNHD_KHContext _db;
        private static int idxInDe = 7;
        private static int idxInDapAn = 8;

        public FormQuanLyDeThi_Export(DotThi dotThi, MySortableBindingList<DeInRa> lstDeThi)
        {
            InitializeComponent();
            _lstDeThi = lstDeThi;
            _dotThi = dotThi;

            _db = DAL.Models.QLNHD_KHContext.GetContext();
            _hocKy = BizHocKy.GetHocKyByMaHK(_dotThi.MaHocKy);
            _namHoc = _hocKy.NamHoc;


            gridDeThi.AutoGenerateColumns = false;
            gridDeThi.DataSource = bsDeThi;
            var lst = new List<DeInRaExportConfig>();
            foreach (var x in lstDeThi)
                lst.Add(new DeInRaExportConfig(x));
            bsDeThi.DataSource = new MySortableBindingList<DeInRaExportConfig>(lst);
            lblHeader.Text = string.Format("{0}", _dotThi.TenDotThi);
        }

        private void btnDeThi_ExportToRtfFile_Click(object sender, EventArgs e)
        {
            gridDeThi.EndEdit();

            var nCheck = 0;
            foreach (DataGridViewRow row in gridDeThi.Rows)
            {
                var de = row.DataBoundItem as DeInRaExportConfig;
                if (de.InDeThi) nCheck++;
                if (de.InDapAn) nCheck++;
            }
            if (nCheck == 0)
            {
                MessageBox.Show("Bạn không đánh dấu chọn để in đề thi và/hoặc đáp án của học phần nào trong danh sách!");
                return;
            }

            string outputFolder = null;
            var dlgFolder = new FolderBrowserDialog();
            if (dlgFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                outputFolder = dlgFolder.SelectedPath;
            else
                return;

            var frm = new FormProgress();
            frm.DoWork += (oSender, oE) =>
            {
                #region MyRegion
                var pnl = new Panel();
                pnl.CreateControl();
                using (var te = TextControlUtils.CreateTextControl())
                {
                    var n = gridDeThi.Rows.Count;
                    for (int i = 0; i < n; i++)
                    {
                        try
                        {
                            var row = gridDeThi.Rows[i];
                            var deInRa = row.DataBoundItem as DeInRaExportConfig;
                            var inDeThi = deInRa.InDeThi;
                            var inDapAn = deInRa.InDapAn;
                            if (!inDeThi && !inDapAn)
                                continue;
                            var tenDeThi = deInRa.TenDeThi; ////STT-MaHocPhan.m1.m2.m3
                            string stNgayThi = deInRa.NgayThi;
                            try
                            {
                                stNgayThi = DateTime.ParseExact(deInRa.NgayThi, "dd/MM/yyyy", null).ToString("yyyyMMdd");
                            }
                            catch { stNgayThi = deInRa.NgayThi; }

                            frm.Worker.ReportProgress((i + 1) * 100 / n, string.Format("{0}/{1}. {2}", i + 1, n, deInRa.TenHocPhan));
                            if (inDeThi) // && !string.IsNullOrEmpty(deInRa.NoiDungDeThi))
                            {
                                var stPath = deInRa.NoiDungDeThi_FullPath();
                                string rtfCode = "";
                                if (System.IO.File.Exists(stPath))
                                    rtfCode = System.IO.File.ReadAllText(stPath);
                                else
                                {
                                    rtfCode = FormDeThi_ChiTiet.GetNoiDungDeThi(pnl, deInRa, _hocKy, _namHoc, _db, true);
                                    BizDeInRa.WriteNoiDungDeThi(deInRa, rtfCode);
                                }

                                te.SetRtfCode(rtfCode, autoReplaceNullContent: false);
                                var stDeFilename = System.IO.Path.Combine(outputFolder, string.Format("DE_{0}_{1}-{2}.rtf", tenDeThi, stNgayThi, deInRa.GioThi));
                                te.SaveToRtfFile(stDeFilename);
                            }
                            if (inDapAn)// && !string.IsNullOrEmpty(deInRa.NoiDungDapAn))
                            {
                                var stPath = deInRa.NoiDungDapAn_FullPath();
                                string rtfCode = "";
                                if (System.IO.File.Exists(stPath))
                                    rtfCode = System.IO.File.ReadAllText(stPath);
                                else
                                {
                                    rtfCode = FormDeThi_ChiTiet.GetNoiDungDapAn(pnl, deInRa, _hocKy, _namHoc, _db, true);
                                    BizDeInRa.WriteNoiDungDapAn(deInRa, rtfCode);
                                }

                                te.SetRtfCode(rtfCode, autoReplaceNullContent: false);
                                var stDapAnFilename = System.IO.Path.Combine(outputFolder, string.Format("DA_{0}_{1}-{2}.rtf", tenDeThi, stNgayThi, deInRa.GioThi));
                                te.SaveToRtfFile(stDapAnFilename);
                            }
                        }
                        catch (Exception exc)
                        {
                            throw;
                        }
                    }
                }
                #endregion
            };
            frm.ProgressChanged += (oSender, oE) =>
            {
                frm.setMessage(oE.UserState.ToString());
            };
            frm.RunWorkerCompleted += (oSender, oE) =>
            {
                frm.Close();
                if (oE.Error != null)
                    MessageBox.Show(oE.Error.ToString());
                System.Diagnostics.Process.Start(outputFolder);
            };

            frm.StartWorking(this);
        }

        private void btnInRaGiay_Click(object sender, EventArgs e)
        {
            gridDeThi.EndEdit();

            var nCheck = 0;
            foreach (DataGridViewRow row in gridDeThi.Rows)
            {
                var de = row.DataBoundItem as DeInRaExportConfig;
                if (de.InDeThi) nCheck++;
                if (de.InDapAn) nCheck++;
            }
            if (nCheck == 0)
            {
                MessageBox.Show("Bạn không đánh dấu chọn để in đề thi và/hoặc đáp án của học phần nào trong danh sách!");
                return;
            }

            PrintDocument printDoc = new PrintDocument();
            printDoc.PrintController = new StandardPrintController();

            var frm = new FormProgress();
            frm.DoWork += (oSender, oE) =>
            {
                #region MyRegion
                var pnl = new Panel();
                pnl.CreateControl();

                using (var te = TextControlUtils.CreateTextControl())
                {
                    var n = gridDeThi.Rows.Count;
                    for (int i = 0; i < n; i++)
                    {
                        try
                        {
                            var row = gridDeThi.Rows[i];
                            var deInRa = row.DataBoundItem as DeInRaExportConfig;
                            var inDeThi = deInRa.InDeThi;
                            var inDapAn = deInRa.InDapAn;
                            if (!inDeThi && !inDapAn)
                                continue;

                            frm.Worker.ReportProgress((i + 1) * 100 / n, string.Format("{0}/{1}. {2}", i + 1, n, deInRa.TenHocPhan));
                            if (inDeThi)// && !string.IsNullOrEmpty(deInRa.NoiDungDeThi))
                            {
                                var stPath = deInRa.NoiDungDeThi_FullPath();
                                string rtfCode = "";
                                if (System.IO.File.Exists(stPath))
                                    rtfCode = System.IO.File.ReadAllText(stPath);
                                else
                                {
                                    rtfCode = FormDeThi_ChiTiet.GetNoiDungDeThi(pnl, deInRa, _hocKy, _namHoc, _db, true);
                                    BizDeInRa.WriteNoiDungDeThi(deInRa, rtfCode);
                                }

                                te.SetRtfCode(rtfCode, autoReplaceNullContent: false);
                                te.Print(printDoc);
                            }
                            if (inDapAn)// && !string.IsNullOrEmpty(deInRa.NoiDungDapAn))
                            {
                                var stPath = deInRa.NoiDungDapAn_FullPath();
                                string rtfCode = "";
                                if (System.IO.File.Exists(stPath))
                                    rtfCode = System.IO.File.ReadAllText(stPath);
                                else
                                {
                                    rtfCode = FormDeThi_ChiTiet.GetNoiDungDapAn(pnl, deInRa, _hocKy, _namHoc, _db, true);
                                    BizDeInRa.WriteNoiDungDapAn(deInRa, rtfCode);
                                }

                                te.SetRtfCode(rtfCode, autoReplaceNullContent: false);

                                te.Print(printDoc);
                            }
                        }
                        catch { }
                    }
                }
                #endregion
            };
            frm.ProgressChanged += (oSender, oE) =>
            {
                frm.setMessage(oE.UserState.ToString());
            };
            frm.RunWorkerCompleted += (oSender, oE) =>
            {
                frm.Close();
            };

            frm.StartWorking(this);
        }

        private void FormQuanLyDeThi_Export_FormClosed(object sender, FormClosedEventArgs e)
        {
            try { _db.Dispose(); }
            catch { }
        }
    }

    [System.ComponentModel.DataAnnotations.Schema.NotMapped]
    public class DeInRaExportConfig : DeInRa
    {
        public bool InDeThi { get; set; }
        public bool InDapAn { get; set; }

        public DeInRaExportConfig()
        { }

        public DeInRaExportConfig(DeInRa deInRa)
        {
            try
            {
                this.HocPhan = deInRa.HocPhan;
                this.NguoiSuDung = deInRa.NguoiSuDung;
                this.DotThi = deInRa.DotThi;
            }
            catch { }

            this.MaDeThi = deInRa.MaDeThi;
            this.MaHocPhan = deInRa.MaHocPhan;
            this.NgayThi = deInRa.NgayThi;
            this.GioThi = deInRa.GioThi;
            this.DuocSuDungTaiLieu = deInRa.DuocSuDungTaiLieu;
            this.InDapAn = false;
            this.InDeThi = true;
            this.LanThi = deInRa.LanThi;
            this.MaDotThi = deInRa.MaDotThi;
            //this.NoiDungDapAn = deInRa.NoiDungDapAn;
            //this.NoiDungDeThi = deInRa.NoiDungDeThi;
            this.TenDangNhap = deInRa.TenDangNhap;
            this.TenDeThi = deInRa.TenDeThi;
            this.ThoiGianLamBai = this.ThoiGianLamBai;
        }
    }
}
